package com.example.springboot.controller;

import com.example.springboot.utils.WebSocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @program: 聊天室
 * @description: ChatRoomServerEndpoint
 * @author: Yuwl
 * @create: 2019-11-25 16:12
 **/
@RestController
@ServerEndpoint("/chat-room/{username}")
public class ChatRoomServerEndpoint {

	private static final Logger LOGGER = LoggerFactory.getLogger(ChatRoomServerEndpoint.class);

	@OnOpen
	public void openSession(@PathParam("username") String username, Session session) {
		WebSocketUtils.LIVING_SESSION_CACHE.put(username, session);
		String message = "欢迎用户[" + username + "]来到聊天室!";
		LOGGER.info("OnOpen: {}", message);
		WebSocketUtils.sendMessageAll(message);
	}

	@OnMessage
	public void onMessage(@PathParam("username") String userrname, String message) {
		message = "用户[" + userrname + "]：" + message;
		LOGGER.info("OnMessage: {}",message);
		WebSocketUtils.sendMessageAll(message);
	}

	@OnClose
	public void onClose(@PathParam("username") String username, Session session) {
		WebSocketUtils.LIVING_SESSION_CACHE.remove(username);
		WebSocketUtils.sendMessageAll("OnClose: 用户[" + username + "]已经离开聊天室了!");
		try {
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@OnError
	public void onError(Session session, Throwable throwable) {
		try {
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		throwable.printStackTrace();
	}

	@GetMapping("/chat-room/{sender}/to/{receiver}")
	public void onMessage(@PathVariable("sender") String sender, @PathVariable("receiver") String receiver, String message) {
		WebSocketUtils.sendMessage(WebSocketUtils.LIVING_SESSION_CACHE.get(receiver), "[" + sender + "] - > [" + receiver + "]：" + message);
	}
}
